<template>
    <div @contextmenu.prevent="showContextMenu">
        <!-- 你的内容区域 -->
        <p>在这里选中文本，然后右键点击可以搜索选中的关键词</p>

        <!-- 右键菜单 -->
        <div v-if="contextMenu.visible" class="context-menu" :style="{
            left: `${contextMenu.x}px`,
            top: `${contextMenu.y}px`
        }">
            <div class="menu-item" @click="searchSelectedText">搜索"{{ selectedText }}"</div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';

const contextMenu = ref({
    visible: false,
    x: 0,
    y: 0
});

const selectedText = ref('');

// 显示右键菜单
const showContextMenu = (event) => {
    // 获取选中的文本
    const text = window.getSelection().toString().trim();

    if (text) {
        selectedText.value = text;
        contextMenu.value = {
            visible: true,
            x: event.clientX,
            y: event.clientY
        };
    }
};

// 点击其他地方关闭菜单
const handleClickOutside = (event) => {
    if (contextMenu.value.visible) {
        // 检查点击是否在菜单外
        const menuElements = document.querySelectorAll('.context-menu');
        let isClickInside = false;

        menuElements.forEach(menu => {
            if (menu.contains(event.target)) {
                isClickInside = true;
            }
        });

        if (!isClickInside) {
            contextMenu.value.visible = false;
        }
    }
};

// 搜索选中的文本
const searchSelectedText = async () => {
    if (!selectedText.value) return;

    try {
        // 调用后端接口
        const response = await axios.post('/api/search', {
            keyword: selectedText.value
        });

        console.log('搜索结果:', response.data);
        // 处理搜索结果，可以跳转页面或显示数据

        // 隐藏菜单
        contextMenu.value.visible = false;
    } catch (error) {
        console.error('搜索失败:', error);
        alert('搜索失败，请重试');
    }
};

// 添加全局点击事件监听
onMounted(() => {
    document.addEventListener('click', handleClickOutside);
});

// 移除事件监听
onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
});
</script>

<style>
.context-menu {
    position: fixed;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    min-width: 150px;
}

.menu-item {
    padding: 8px 12px;
    cursor: pointer;
}

.menu-item:hover {
    background-color: #f5f5f5;
}
</style>